/*
 * Copyright(C) 2010 Luvina Software Company
 *
 * AjaxServlet.java, Oct 29, 2010 ntmhuong
 */
package net.luvina.manageuser.servlet;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

/**
 * Ajaxリクエストの受付サーブレット
 *
 * @version $Rev$
 */
public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String AJAX_METHOD_NAME = "doAjax";
    private static final String EMPTY_RESPONSE = "[]";
    private Map<String, String> ajaxMap = new HashMap<String, String>();

    /**
     * 利用可能なAjax一覧
     */
    public void init() {
        // Ajax機能一覧（キー、ManagedBeanのクラス名）
        /*this.ajaxMap.put("session_heart_beat", "jp.co.sms.kaipokebiz.ajax.SessionHeartBeatAjax");
        this.ajaxMap.put("check_login", "jp.co.sms.kaipokebiz.ajax.CheckLoginAjax");
        this.ajaxMap.put("do_login", "jp.co.sms.kaipokebiz.ajax.DoLoginAjax");*/

        this.ajaxMap.put("list_care_member", "jp.co.sms.kaipokebiz.ajax.ListCareMemberAjax");
    }

    /**
     * 各種Ajax処理を実行し、結果をJson形式で出力
     *
     * @param request   HttpServletRequest
     * @param response  HttpServletResponse
     */
    public void service(HttpServletRequest request, HttpServletResponse response) {
        try {
            // レスポンス設定
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter out = response.getWriter();
            String className = this.ajaxMap.get(request.getParameter("function"));
            if (className != null) {
                // Ajax処理呼び出し
                Class<?> cls = Class.forName(className);
                Method method = cls.getMethod(AJAX_METHOD_NAME, new Class[]{ServletContext.class, HttpServletRequest.class, HttpServletResponse.class});
                try {
                    Object ret = method.invoke(cls.newInstance(), new Object[]{getServletContext(), request, response});
                    JSONObject jsonObject = JSONObject.fromObject(ret);
                    out.print(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                    out.print(EMPTY_RESPONSE);
                }
            } else {
                out.print(EMPTY_RESPONSE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}
